/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ble.juanyuan.yuntai;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.*;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;


//对于给定的ble设备，这个activity提供接口去连接，展示数据，service和characteris。
//The Activity communicates with {@code BluetoothLeService}, which in turn interacts with the Bluetooth LE API.
public class DeviceControlActivity extends Activity {
    private final static String TAG = DeviceControlActivity.class.getSimpleName();

    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    private TextView mConnectionState;
    private TextView mDataField;
//    private Button openBulb;
//    private EditText setTimeText;   //接受数据输入句柄
//    private Button setTimeBtn;    //接受定时开关指令

    EditText YN ;
    EditText EveryCircleCount ;
    CheckBox AutoCamera ;

    EditText XSpeed ;
    EditText YSpeed ;

    TextView Xangle;
    TextView Yangle;
    TextView WorkState;


    private String mDeviceName;
    private String mDeviceAddress;
    /*private ExpandableListView mGattServicesList;*/
    private BluetoothLeService mBluetoothLeService;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
            new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    private boolean mConnected = false;
    private BluetoothGattCharacteristic mNotifyCharacteristic;

    private final String LIST_NAME = "NAME";
    private final String LIST_UUID = "UUID";


    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up initialization.
           try {
               mBluetoothLeService.connect(mDeviceAddress);
           }catch (Exception e){
               System.out.println(e.getMessage());
           }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    //BroadcastReceiver：从service中传回来的参数，从BluetoothLeService中Broadcast中传回来的参数
    //若广播是service状态的改变（连接，未连接，发现，获得data）
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            //若广播是service状态的改变（连接，未连接，发现，获得data）
           /* if ((mNotifyCharacteristic == null) || ((0x10 | mNotifyCharacteristic.getProperties()) <= 0)){
                return;
            }*/
           //Toast.makeText(getApplicationContext(),"action:"+action,Toast.LENGTH_SHORT).show();
           /* DeviceControlActivity.this.mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, true);*/
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                updateConnectionState(R.string.connected);
                invalidateOptionsMenu();
                //TODO 刚加上
                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                updateConnectionState(R.string.disconnected);
                invalidateOptionsMenu();
                clearUI();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
                //TODO在此处修改了，使得发现服务后直接开启获得数据
               mNotifyCharacteristic = mBluetoothLeService.getBluetoothGattCharacteristic();
                if ((mNotifyCharacteristic == null) || ((0x10 | mNotifyCharacteristic.getProperties()) <= 0)) {
                    return;
                }
               mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, true);
                //TODO 刚加上
                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                //TODO在此处修改了，使得发现服务后直接开启获得数据
                mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic,true);
                //displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));


                //这里添加接收数据代码
                //byte[] bytes = mNotifyCharacteristic.getValue();
                byte[] bytes=intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                displayData(bytes);

                if (bytes!=null)
                {
                    if (bytes[0]==(byte) 0xAA && bytes[1]==(byte) 0xBB)
                    {
                        Integer xangle = bytes[2]>0 ? bytes[3]+0xFF : bytes[3];
                        Integer yangle = new Integer(bytes[4]);
                        Boolean worksstate = bytes[5]>0?true:false;

                        DisplayState(xangle, yangle, worksstate);
                    }
                }

                //使得定时的textview里面不显示数据
                /*String str2 = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
                setTimeText.setText(str2);*/
            }
        }
    };

    // 演示如何迭代所支持的GATT Services/Characteristics.
    // 在这个例子中，我们填充绑定到ExpandableListView的数据结构。
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;
        String uuid = null;
        String unknownServiceString = getResources().
                getString(R.string.unknown_service);
        String unknownCharaString = getResources().
                getString(R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData =
                new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics =
                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // 循环迭代可访问的GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData =
                    new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(
                    LIST_NAME, SampleGattAttributes.
                            lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
                    new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas =
                    new ArrayList<BluetoothGattCharacteristic>();
            // 循环迭代可访问的Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData =
                        new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(
                        LIST_NAME, SampleGattAttributes.lookup(uuid,
                                unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }
    }

        //设备未连接时清除界面内容
    private void clearUI() {
       /* mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);*/
        mDataField.setText(R.string.no_data);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gatt_services_characteristics);

        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

        // Sets up UI references.
        ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
        /*mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);*/
        /*mGattServicesList.setOnChildClickListener(servicesListClickListner);*/
        mConnectionState = (TextView) findViewById(R.id.connection_state);
        mDataField = (TextView) findViewById(R.id.data_value);
        YN = (EditText) findViewById(R.id.YN);
        EveryCircleCount = (EditText) findViewById(R.id.EveryCircleCount);
        AutoCamera = (CheckBox) findViewById(R.id.AutoCamera);
        XSpeed = (EditText)findViewById(R.id.XSpeed);
        YSpeed = (EditText)findViewById(R.id.YSpeed);

        Xangle = (TextView)findViewById(R.id.Xangle);
        Yangle = (TextView)findViewById(R.id.Yangle);
        WorkState = (TextView)findViewById(R.id.Workstate);

//        openBulb = (Button)findViewById(R.id.openBulb) ;
//        setTimeText = (EditText) findViewById(R.id.setTimeText);
//        setTimeBtn = (Button) findViewById(R.id.setTimeBtn);


//        getActionBar().setTitle(mDeviceName);
//        getActionBar().setDisplayHomeAsUpEnabled(true);
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        updateConnectionState(R.string.connecting);
    }

    //重启时、开始时注册广播
    @Override
    protected void onResume() {
        super.onResume();
        //注册广播
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }

    //停止时，注销广播
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }

    //关闭activity
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }

    //判断是否连接，若未连接就展示没有连接的设备
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.gatt_services, menu);
        if (mConnected) {
            menu.findItem(R.id.menu_connect).setVisible(false);
            menu.findItem(R.id.menu_disconnect).setVisible(true);
        } else {
            menu.findItem(R.id.menu_connect).setVisible(true);
            menu.findItem(R.id.menu_disconnect).setVisible(false);
        }
        return true;
    }

    //主菜单item被点击之后，intend获取来自deviceScanActivity的address和name从而进行连接
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_connect:
                mBluetoothLeService.connect(mDeviceAddress);
                return true;
            case R.id.menu_disconnect:
                mBluetoothLeService.disconnect();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //显示当前连接状态
    private void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mConnectionState.setText(resourceId);
            }
        });
    }

    //显示传来的数据
    private void displayData(String data) {
        if (data != null) {
           /* mDataField.append(data);*/
            mDataField.setText(data);
        }
    }

    private void displayData(byte[] data) {
        if (data!=null)
            mDataField.setText(HexConvert.bytesToHexString(data));
    }

    /**
     * 显示状态 接收数据
     * @param xangle
     * @param yangle
     * @param worksstate
     */
    private void DisplayState(Integer xangle, Integer yangle, Boolean worksstate) {
        if (xangle!=null&& yangle!=null&&worksstate!=null) {
            Xangle.setText(xangle.toString());
            Yangle.setText(yangle.toString());
            WorkState.setText(worksstate ? R.string.Working : R.string.Stop);
        }
    }

/*    //开灯按键响应函数
    public void onSwitchBulbClicked(View v) {
        if (mConnected = false) {
            Toast.makeText(DeviceControlActivity.this, "请先连接设备", Toast.LENGTH_SHORT).show();
        } else {
            if (openBulb.getText() == "开灯") {
               *//* sendMsg("Sapp_mode1E");*//*
                sendMsg("Sopen_led1E");
              *//*  openBulb.getBackground().setAlpha(50);
                setTimeBtn.getBackground().setAlpha(50);*//*
                openBulb.setText("关灯");
                setTimeBtn.setText("定时关灯");
            } else*//* if (openBulb.getText() == "关灯")*//* {
                *//*sendMsg("Sapp_mode1E");*//*
                sendMsg("Sclose_led1E");
                *//*openBulb.getBackground().setAlpha(200);
                setTimeBtn.getBackground().setAlpha(200);*//*
                openBulb.setText("开灯");
                setTimeBtn.setText("定时开灯");
            }

        }
    }



    //定时发送开关灯命令
    public  void onSetTimeOpenBulb(View v){
        //转化成是string类型
        String mText = setTimeText.getText().toString();
        sendMsg(mText);
        //判断用户输入的定时是否是数字
        //TODO 对用户定时的时间是否有要求
        *//*Pattern p = Pattern.compile("[^6]");//[0-9]*
        Matcher m = p.matcher(mText);
        if (mText.equals("")){
            Toast.makeText(DeviceControlActivity.this, "请先输入时间", Toast.LENGTH_SHORT).show();
        }else{
            if (m.matches()){
                if (setTimeBtn.getText() == "定时开灯"){
                    sendMsg("Sopen:"+mText+"E");
                    Toast.makeText(DeviceControlActivity.this, "在"+mText+"分钟后"+setTimeBtn.getText(), Toast.LENGTH_SHORT).show();
                    setTimeText.setText(null);
                    openBulb.getBackground().setAlpha(50);
                    setTimeBtn.getBackground().setAlpha(50);
                    setTimeBtn.setText("定时关灯");
                    openBulb.setText("关灯");
                }else*//**//* if (setTimeBtn.getText() == "定时开灯")*//**//*{
                    sendMsg("Sclose:"+mText+"E");
                    Toast.makeText(DeviceControlActivity.this, "在"+mText+"分钟后"+setTimeBtn.getText(), Toast.LENGTH_SHORT).show();
                    setTimeText.setText(null);
                    openBulb.getBackground().setAlpha(200);
                    setTimeBtn.getBackground().setAlpha(200);
                    setTimeBtn.setText("定时开灯");
                    openBulb.setText("开灯");
                }
            }else{
                Toast.makeText(DeviceControlActivity.this, "请输入数字", Toast.LENGTH_SHORT).show();
            }
        }*//*
    }*/



    /**
     * 生成运行参数
     * @return
     */
    private byte[] GenerateData(){
        String[] YStr = YN.getText().toString().trim().split(" ");
        int bytes_length=YStr.length+7;//7个字节位固定位
        byte[] sendbytesData = new  byte[bytes_length];
        byte[] bytesY = GenerateY();//纵向角度 Yn

        //协议表约定
        sendbytesData[0]=(byte) 0xDD;//纵向角度结束符
        for (int i=0;i<bytesY.length;i++)
        {
            sendbytesData[i+1]=bytesY[i];
        }

        sendbytesData[bytesY.length+1]=GenerateXYSpeed();//高半字节为X向速度 低半字节为 Y向速度



        sendbytesData[bytesY.length+2]=Byte.parseByte(EveryCircleCount.getText().toString());//每圈拍照次数

        sendbytesData[bytesY.length+3]=(byte) 0xAA;//纵向角度结束位
        sendbytesData[bytesY.length+4]=(byte)0xBB;//纵向角度结束位
        sendbytesData[bytesY.length+5]=(byte) (AutoCamera.isChecked()?0x01:0x00);//自动拍照
        byte bt=0;
        for (int i=0;i<sendbytesData.length-1;i++)
        {
            bt+=sendbytesData[i];
        }
        sendbytesData[sendbytesData.length-1]=bt;//校验和


        return sendbytesData;
    }

    /**
     * 获取XY向速度 高字节位X向速度 低字节位Y向速度
     * @return
     */
    private byte GenerateXYSpeed(){
        byte Xbyte =Byte.parseByte(XSpeed.getText().toString());
        byte Ybyte =Byte.parseByte(YSpeed.getText().toString());
        byte XYSpeed = (byte)((Xbyte<<4)|Ybyte);
        return XYSpeed;
    }

    /**
     * s获取Y向角字节数据
     * @return 约定的格式排列
     */
    private byte[] GenerateY() {

        String[] YStr = YN.getText().toString().trim().replaceAll(" +", " ").split(" ");//字符数组 去掉多余空格

        byte[] tempY = new byte[YStr.length];
        for (int i=0;i<tempY.length;i++)
        {
            tempY[i] = (byte)Integer.parseInt(YStr[tempY.length-i-1]);
        }

        for (int i=0;i<tempY.length-1;i++)
        {
            tempY[i]-=tempY[i+1];
        }
        return tempY;
    }

    /**
     * 发送控制命令
     * @param control 0 回原点 1 启动 2 停止
     */
    private void SendControl(int control)
    {
        /* 1  帧头  0xFF 2  帧头  0xEE  3    命令类型  1：回原点  2：启动 3：停止      4  校验和  前面 3 字节的校验和*/
        byte[] bytes = new byte[4];
        bytes[0]=(byte)0xFF;
        bytes[1]=(byte)0xEE;
        bytes[2]=(byte)control;
        int value =bytes[0]+bytes[1]+bytes[2];
        bytes[3] = (byte)(value%255);
        sendMsg(bytes);

        TextView dataView = (TextView) findViewById(R.id.data_value);
        dataView.setText(HexConvert.bytesToHexString(bytes));
    }

    /**
     * 发送数据
     * @param v
     */
    public void onSendData(View v){
        byte[] data=null;
        try {
            data = GenerateData();
            sendMsg(data);
        }
        catch (Exception ex)
        {
            Toast.makeText(this,ex.getMessage(),Toast.LENGTH_SHORT).show();
        }
        TextView dataView = (TextView) findViewById(R.id.data_value);
        dataView.setText(HexConvert.bytesToHexString(data));
    }

    /**
     * 回原点
     * @param v
     */
    public void onSendResetControl(View v){
        SendControl(1);
    }

    /***
     * 启动
     * @param v
     */
    public void onSendStartControl(View v){
        SendControl(2);
    }

    /**
     * 停止
     * @param v
     */
    public void onSendStopControl(View v){
        SendControl(3);
    }

    /**
     * 断开蓝牙
     * @param v
     */
    public void onDisConnect(View v){
        mBluetoothLeService.disconnect();
    }

    public void onReconnect(View v){
        mBluetoothLeService.connect(mDeviceAddress);
        updateConnectionState(R.string.connecting);
    }

    //发送字节消息
    public void sendMsg(byte[] bytes)
    {
        if ((mNotifyCharacteristic == null) || (bytes == null)){
            return;
        }
        if ((BluetoothGattCharacteristic.PROPERTY_WRITE | mNotifyCharacteristic.getProperties()) > 0){
            byte[] arrayOfByte2 = new byte[20];
            arrayOfByte2[0] = 0;
            mNotifyCharacteristic.setValue(arrayOfByte2[0], 0x11, 0);
            mNotifyCharacteristic.setValue(bytes);
            this.mBluetoothLeService.writeCharacteristic(mNotifyCharacteristic);


        }
    }

    //发送字符消息
    public void sendMsg(String paramString)
    {
        if ((mNotifyCharacteristic == null) || (paramString == null)){
            return;
        }
        if ((0x8 | mNotifyCharacteristic.getProperties()) <= 0){
            return;
        }
        byte[] arrayOfByte1 = new byte[20];
        byte[] arrayOfByte2 = new byte[20];
        arrayOfByte2[0] = 0;
        if (paramString.length() > 0){
            arrayOfByte1 = paramString.getBytes();
        }
       mNotifyCharacteristic.setValue(arrayOfByte2[0], 0x11, 0);
        mNotifyCharacteristic.setValue(arrayOfByte1);
        this.mBluetoothLeService.writeCharacteristic(mNotifyCharacteristic);
    }

    //注册广播时定义intent的各种属性
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

}


